#include <iostream>
#include <string>
#include <functional>
#include <cassert>
#include "Log.hpp"
#include "Sock.hpp"
#include "Epoll.hpp"

namespace ns_epoll
{
    const static int default_port = 8080;
    const static int gnum = 64;

    class EpollServer
    {
        using func_t = std::function<void(std::string)>;

    public:
        EpollServer(func_t HandlerRequest, const int &port = default_port)
            : _port(port), _revs_num(gnum), _HandlerRequest(HandlerRequest)
        {
            _revs = new struct epoll_event[_revs_num];
            _listensock = Sock::Socket();
            Sock::Bind(_listensock, _port);
            Sock::Listen(_listensock);

            _epfd = Epoll::CreateEpoll();
            logMessage(DEBUG, "mag add listensock to epoll success!");
        }

        void HandlerEvents(int n)
        {
            assert(n > 0);
            for (int i = 0; i < n; i++)
            {
                uint32_t revents = _revs[i].events;
                int sock = _revs[i].data.fd;
                // 读事件就绪进行处理
                if (revents & EPOLLIN)
                {
                    if (sock == _listensock)
                        Accepter(_listensock);
                    else
                    //此时证明等待队列，已经有相应sock在等待了；所以让该sock去读取相应的数据
                        Recver(sock);
                }
                if (revents & EPOLLOUT)
                {

                }
            }
        }

        void Accepter(int listensock)
        {
            std::string clientip;
            uint16_t clientport;
            int sock = Sock::Accept(listensock, &clientip, &clientport);
            if (sock < 0)
            {
                logMessage(WARNING, "accept error");
                return;
            }
            // 添加成功返回0
            if (!Epoll::CtlEpoll(_epfd, EPOLL_CTL_ADD, sock, EPOLLIN))
                return;
            logMessage(DEBUG, "add new sock : %d to epoll success!", sock);
        }

        void Recver(int sock)
        {
            char buffer[102400];
            ssize_t n = recv(sock, buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                _HandlerRequest(buffer);
            }
            else if (n == 0)
            {
                // 删除文件描述符并关闭套接字
                bool res = Epoll::CtlEpoll(_epfd, EPOLL_CTL_DEL, sock, 0);
                assert(res);
                (void)res;
                close(sock);
                logMessage(NORMAL, "client %d quit ,me too...", sock);
            }
            else
            {
                bool res = Epoll::CtlEpoll(_epfd, EPOLL_CTL_DEL, sock, 0);
                assert(res);
                (void)res;
                close(sock);
                logMessage(NORMAL, "client %d errror ,close error sock", sock);
            }
        }

        void LoopOnce(int timeout)
        {
            int n = Epoll::WaitEpoll(_epfd, _revs, _revs_num, timeout);
            switch (n)
            {
            case 0:
                logMessage(DEBUG, "timeout..."); // 3, 4
                break;
            case -1:
                logMessage(WARNING, "epoll wait error: %s", strerror(errno));
                break;
            default:
                // 等待成功
                logMessage(DEBUG, "get a event");
                HandlerEvents(n);
                break;
            }
        }

        void Start()
        {
            int timeout =10;
            while (true)
            {
                LoopOnce(timeout);
            } 
        }

        ~EpollServer()
        {
            if(_listensock>=0)
            {
                close(_listensock);
            }
            if(_epfd>=0)
            {
                close(_epfd);
            }
            if(_revs)
            {
                delete[] _revs;
            }
        }

    private:
        int _listensock;
        int _epfd;
        uint16_t _port;
        struct epoll_event *_revs;
        int _revs_num;
        func_t _HandlerRequest;
    };

} // namespace ns_epoll
